package com.barunlab.ems.server.sms.main;

import java.io.File;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.log4j.Logger;

import com.barunlab.ems.server.main.ServerProperties;
import com.barunlab.ems.server.sms.control.SMSReceiver;


public class SMSMain {
	private static Logger LOGGER = Logger.getLogger(SMSMain.class);
	
	public SMSMain(String[] configFiles) {
		try {
			initConfig(configFiles);
			initRmi();
		}
		catch (Exception ex) {
			LOGGER.error(ex.getMessage(), ex);
		}
	}
	
	private void initConfig(String[] configFiles) throws Exception {
		ServerProperties.load(configFiles);
		
		LOGGER.info("Configuration loaded.");
	}
	
	private void initRmi() throws Exception {
		Registry registry = LocateRegistry.createRegistry(ServerProperties.RMI_PORT);
		
		SMSReceiver receiver = SMSReceiver.getInstance();
		
		registry.rebind(ServerProperties.RMI_SMS_BIND_NAME, receiver);
		
		String bindMsg = String.format("Registry bound SMS(%s/%s)", 
				ServerProperties.RMI_SMS_BIND_NAME, ServerProperties.RMI_PORT);
		
		LOGGER.info(bindMsg);
	}
	
	public static void main(String[] args) {
		String configFile = null;
		
		if ( args.length < 1 ) {
			System.err.println("Usage: java SMSMain configFile");
			System.exit(1);
		}
		else {
			for ( int i = 0; i < args.length; i++ ) {
				configFile = args[i];
				
				File file = new File(configFile);
				if ( file.exists() == false ) {
					System.err.println(String.format("Config file(%s) doesn't exist.", configFile));
					System.exit(1);
				}
			}
		}
		
		new SMSMain(args);
		
		LOGGER.info("SMS started.");
	}
}
